package com.jie.langlangmall.portal.service.impl;

import cn.hutool.core.util.StrUtil;
import com.jie.langlangmall.common.constant.MessageConstant;
import com.jie.langlangmall.common.constant.StatusConstant;
import com.jie.langlangmall.common.exception.ApiException;
import com.jie.langlangmall.mapper.UmsMemberLevelMapper;
import com.jie.langlangmall.mapper.UmsMemberMapper;
import com.jie.langlangmall.model.UmsMember;
import com.jie.langlangmall.model.UmsMemberExample;
import com.jie.langlangmall.model.UmsMemberLevel;
import com.jie.langlangmall.model.UmsMemberLevelExample;
import com.jie.langlangmall.portal.domain.MemberDetails;
import com.jie.langlangmall.portal.service.UmsMemberCacheService;
import com.jie.langlangmall.portal.service.UmsMemberService;
import com.jie.langlangmall.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author Jie
 * @Date 2024/11/25
 * @Email 3217998214@qq.com
 * @Description 会员
 */
@Service
@Slf4j
public class UmsMemberServiceImpl implements UmsMemberService {

    @Autowired
    private UmsMemberCacheService memberCacheService;
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 获取用户信息
     *
     * @param username
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        UmsMember member = getByUsername(username);
        if (member != null) {
            return new MemberDetails(member);
        }
        throw new UsernameNotFoundException(MessageConstant.USERNAME_OR_PASSWORD_ERROR);
    }

    @Override
    public UmsMember getByUsername(String username) {
        // 从缓存中查询
        UmsMember member = memberCacheService.getMember(username);
        if (member != null) return member;
        // 从数据库中查询
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            member = memberList.get(0);
            memberCacheService.setMember(member);
            return member;
        }
        return null;
    }

    /**
     * 注册
     *
     * @param username
     * @param password
     * @param telephone
     * @param authCode
     */
    @Override
    public void register(String username, String password, String telephone, String authCode) {
        // 校验验证码
        if (!verifyAuthCode(authCode, telephone)) {
            throw new ApiException(MessageConstant.AUTH_CODE_ERROR);
        }
        // 查询该用户是否已经注册账号
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        example.or(example.createCriteria().andPhoneEqualTo(telephone));
        if (memberMapper.countByExample(example) > 0) {
            throw new ApiException(MessageConstant.USERNAME_OR_TELEPHONE_EXIST);
        }
        // 没有用户则注册
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(username);
        umsMember.setPhone(telephone);
        umsMember.setPassword(passwordEncoder.encode(password));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(StatusConstant.ENABLE);
        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        umsMember.setPassword(null);
    }

    /**
     * 登录，返回token
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public String login(String username, String password) {
//        log.info(password);
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            log.info(userDetails.toString());
            log.info(passwordEncoder.encode(password));
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException(MessageConstant.PASSWORD_ERROR);
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return
     */
    @Override
    public UmsMember getCurrentMember() {
        // 获取SpringBoot上下文
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
        return memberDetails.umsMember();
    }

    /**
     * 获取验证码
     *
     * @param telephone
     * @return
     */
    @Override
    public String generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        memberCacheService.setAuthCode(telephone, sb.toString());
        // TODO: 实现手机号发送验证码的功能
        log.info("生成验证码：{}", sb);
        return sb.toString();
    }

    /**
     * 修改密码
     *
     * @param telephone
     * @param password
     * @param authCode
     */
    @Override
    public void updatePassword(String telephone, String password, String authCode) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(memberList)) {
            throw new ApiException(MessageConstant.ACCOUNT_NOT_EXIST);
        }
        //验证验证码
        if (!verifyAuthCode(authCode, telephone)) {
            throw new ApiException(MessageConstant.AUTH_CODE_ERROR);
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(passwordEncoder.encode(password));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        // 更新缓存
        memberCacheService.delMember(umsMember.getId());
    }

    /**
     * 刷新token
     *
     * @param token
     * @return
     */
    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }

    /**
     * 修改积分值
     * @param id
     * @param integration
     */
    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record = new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
        memberCacheService.delMember(id);
    }

    /**
     * 根据ID获取
     * @param memberId
     * @return
     */
    @Override
    public UmsMember getById(Long memberId) {
        return memberMapper.selectByPrimaryKey(memberId);
    }


    /**
     * 校验验证码
     *
     * @param authCode
     * @param telephone
     * @return
     */
    private boolean verifyAuthCode(String authCode, String telephone) {
        if (StrUtil.isEmpty(authCode)) {
            return false;
        }
        // 从缓存中获取验证码
        String realAuthCode = memberCacheService.getAuthCode(telephone);
        return authCode.equals(realAuthCode);
    }


}
